package impl

import (
	"errors"
	"gitee.com/hexug/vblog/tree/master/api/apps"
	"gitee.com/hexug/vblog/tree/master/api/apps/user"
	"gitee.com/hexug/vblog/tree/master/api/conf"
	"github.com/google/uuid"
	"sync"
)

var (
	// Sessions session存储的大map，支持并发
	Sessions sync.Map
)

type impl struct {
	Auth *conf.Auth
}

// CreatSession 创建session
func CreatSession(request *user.LoginRequest) (*user.Session, error) {
	//在session的map中查找
	if value, ok := Sessions.Load(request.UserName); ok {
		//如果已经存在，就直接返回对应的session
		s := user.NewSession(value.(string), request.UserName)
		return s, nil
	}
	//如果没有，就新建session
	u, err := uuid.NewUUID()
	if err != nil {
		return nil, err
	}
	//将新建的session加入到大map中
	Sessions.Store(request.UserName, u.String())
	s := user.NewSession(u.String(), request.UserName)
	//返回session
	return s, nil
}

// DeleteSession 删除session
func DeleteSession(request *user.LogoutRequest) error {
	//在大map中查找，看下是否存在
	if value, ok := Sessions.Load(request.UserName); ok {
		//存在，就比较请求携带的session与服务器保存的session是否相等
		if value.(string) == request.Session {
			//相等就从大map中删除对应的session
			Sessions.Delete(request.UserName)
			return nil
		} else {
			return errors.New("验证未通过~")
		}
	} else {
		return errors.New("尚未登录！")
	}
}

func (i *impl) Name() string {
	return user.AppName
}

func (i *impl) Init() error {
	i.Auth = conf.C().Auth
	return nil
}

// 初始化注册app
func init() {
	apps.RegisterApp(&impl{})
}
